package epidemic

import (
	"encoding/json"
	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/model/common/request"
	"gitee.com/baal1990/epidemic/model/epidemic"
	epidemicReq "gitee.com/baal1990/epidemic/model/epidemic/request"
	epidemicRsp "gitee.com/baal1990/epidemic/model/epidemic/response"
	"gitee.com/baal1990/epidemic/utils/msgsms"
	"gitee.com/baal1990/epidemic/utils/prepare"
	"strings"
	"time"
)

type EpidemicInvestigationFormService struct {
}

// CreateEpidemicInvestigationForm 创建EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) CreateEpidemicInvestigationForm(epidemicInvestigationForm epidemic.EpidemicInvestigationForm) (err error) {
	db := global.GVA_DB
	err = db.Create(&epidemicInvestigationForm).Error
	if err != nil {
		return err
	}
	err = createEpidemicDetailUser(epidemicInvestigationForm)
	return err
}

// DeleteEpidemicInvestigationForm 删除EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) DeleteEpidemicInvestigationForm(id string) (err error) {
	err = global.GVA_DB.Where("id=?", id).Delete(&epidemic.EpidemicInvestigationForm{}).Error
	return err
}

// DeleteEpidemicInvestigationFormByIds 批量删除EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) DeleteEpidemicInvestigationFormByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]epidemic.EpidemicInvestigationForm{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateEpidemicInvestigationForm 更新EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) UpdateEpidemicInvestigationForm(epidemicInvestigationForm epidemic.EpidemicInvestigationForm) (err error) {
	err = global.GVA_DB.Omit("publish_date", "status").
		Save(&epidemicInvestigationForm).Error
	if err != nil {
		return err
	}
	//更新时候先删掉再创建
	db := global.GVA_DB
	err = db.Where("related_form_id=?", epidemicInvestigationForm.ID).Delete(&epidemic.EpidemicInvestigationDetails{}).Error
	if err != nil {
		return err
	}
	err = createEpidemicDetailUser(epidemicInvestigationForm)
	return err
}

// 生成部门的in条件
func genDepartmentCondition(departments string) string {
	departmentSlice := strings.Split(departments, ",")
	condition := ""
	lastIndex := len(departmentSlice) - 1
	for i, e := range departmentSlice {
		condition += "'" + e + "'"
		if i != lastIndex {
			condition += ","
		}
	}
	return condition
}

/*
*
创建疫情排查详情表用户
*/
func createEpidemicDetailUser(epidemicInvestigationForm epidemic.EpidemicInvestigationForm) (err error) {
	db := global.GVA_DB
	var epidemicUsers []epidemic.EpidemicUser
	err = db.Create(&epidemicInvestigationForm).Error
	err = db.Model(&epidemic.EpidemicUser{}).
		Where("company=? and department in ("+genDepartmentCondition(epidemicInvestigationForm.Department)+") and location = ? and status=?",
			epidemicInvestigationForm.Company, epidemicInvestigationForm.Location, global.DICT_USER_APPROVED_STATUS).
		Find(&epidemicUsers).Error
	for i := 0; i < len(epidemicUsers); i++ {
		var epidemicInvestigationDetails epidemic.EpidemicInvestigationDetails
		epidemicInvestigationDetails.RelatedFormId = epidemicInvestigationForm.ID
		epidemicInvestigationDetails.Mobile = epidemicUsers[i].Mobile
		epidemicInvestigationDetails.Status = global.DICT_INVESTIGATION_WRITE_STATUS_UNFILL  //数据字典 2是未填
		epidemicInvestigationDetails.Abnormal = global.DICT_INVESTIGATION_USER_STATUS_ENABLE //数据字典 1是正常
		epidemicInvestigationDetails.Remarks = ""
		err = global.GVA_DB.Create(&epidemicInvestigationDetails).Error
	}
	return err
}

// GetEpidemicInvestigationForm 根据id获取EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) GetEpidemicInvestigationForm(id uint) (epidemicInvestigationForm epidemic.EpidemicInvestigationForm, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&epidemicInvestigationForm).Error
	return
}

// GetEpidemicInvestigationFormInfoList 分页获取EpidemicInvestigationForm记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) GetEpidemicInvestigationFormInfoList(info epidemicReq.EpidemicInvestigationFormSearch, user epidemic.EpidemicUser) (list []epidemic.EpidemicInvestigationForm, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicInvestigationForm{})
	if user.Role != global.DICT_ROLES_SUPER {
		db = db.Where("company=? and department in ?", user.Company, prepare.Department(user.Department))
	}

	var epidemicInvestigationForms []epidemic.EpidemicInvestigationForm
	db = db.Where("status != ?", global.DICT_INVESTIGATION_FORM_STATUS_Delete) //不等于删除状态

	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Title != "" {
		db = db.Where("title like ?", "%"+info.Title+"%")
	}
	if info.Status != "" {
		db = db.Where("status= ?", info.Status)
	}
	if info.PublishDate != "" {
		db = db.Where("DATE(publish_date)= ?", info.PublishDate)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&epidemicInvestigationForms).Error
	return epidemicInvestigationForms, total, err
}

// 用户侧
// 首页疫情排查列表
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) GetEpidemicInvestigationFormInfoListUserSide(info epidemicReq.EpidemicInvestigationFormListUserSide, mobile string) (list []epidemic.EpidemicInvestigation, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB
	var epidemicInvestigationForms []epidemic.EpidemicInvestigation
	// 获取疫情排查表状态-关闭
	closeStatus, err := GetValueByKeyAndName("investigation_form_status", "关闭")
	deleteStatus, err := GetValueByKeyAndName("investigation_form_status", "删除")

	if err != nil {
		return
	}
	db = db.Table("epidemic_investigation_form A").
		Where("mobile=? and A.status not in (?,?)", mobile, closeStatus, deleteStatus).
		Joins("join epidemic_investigation_details B on A.id=B.related_form_id").
		Select("A.id,A.title,A.content,A.link,A.url_link,A.questions,B.status,B.answer,B.special_situation")

	// 增加状态过滤条件
	allStatus, err := GetValueByKeyAndName("investigation_write_status", "全部")
	if allStatus != "" && allStatus != info.Status {
		db.Where("B.status=?", info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&epidemicInvestigationForms).Error
	return epidemicInvestigationForms, total, err
}

// 用户侧
// 疫情排查表填报
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) EpidemicInvestigationFormCheckinUserSide(req epidemicReq.EpidemicInvestigationFormCheckinUserSide) (err error) {
	// 登记epidemic_investigation_details表的填报状态、涉疫异常状态
	var form epidemic.EpidemicInvestigationForm
	db := global.GVA_DB.Model(&epidemic.EpidemicInvestigationForm{})
	db1 := global.GVA_DB.Model(&epidemic.EpidemicInvestigationDetails{})
	err = db.Where("id=?", req.Id).Find(&form).Error
	if err != nil {
		return
	}
	//如果是打开状态，转换为进行中
	if form.Status == global.DICT_INVESTIGATION_FORM_STATUS_OPEN {
		form.Status = global.DICT_INVESTIGATION_FORM_STATUS_Doing
	}

	var questions epidemicRsp.EpidemicInvestigationFormQuestions
	err = json.Unmarshal([]byte(form.Questions), &questions)
	if err != nil {
		return
	}
	var detail epidemic.EpidemicInvestigationDetails
	if err = db1.Where("mobile=? and related_form_id=?", req.Mobile, req.Id).Find(&detail).Error; err != nil {
		return
	}
	// 疫情排查表填报状态-已填
	detail.Status, err = GetValueByKeyAndName("investigation_write_status", "已填")
	if err != nil {
		return
	}
	detail.Answer = req.Answers
	detail.SpecialSituation = req.SpecialSituation
	answerSlice := strings.Split(req.Answers, ",")
	for i := 0; i < len(answerSlice); i++ {
		if answerSlice[i] == questions.Questions[i].Criteria { // 存在异常
			// 员工涉疫状态-异常
			detail.Abnormal, err = GetValueByKeyAndName("investigation_user_status", "异常")
			if err != nil {
				return
			}
			break
		} else {
			detail.Abnormal, err = GetValueByKeyAndName("investigation_user_status", "正常")
			if err != nil {
				return
			}
		}
	}
	now := time.Now()
	detail.UpdateTime = &now
	if detail.ReporteTime == nil {
		detail.ReporteTime = &now
		db1 = db1.Select("abnormal", "status", "answer", "special_situation", "reporte_time", "update_time")
	} else {
		db1 = db1.Select("abnormal", "status", "answer", "special_situation", "update_time")
	}
	if err = db1.Updates(&detail).Error; err != nil {
		return
	}
	// 维护epidemic_investigation_form表异常统计
	// 获取details表中异常总数
	var total int64 = 0
	// 员工涉疫状态-异常
	abnormal, err := GetValueByKeyAndName("investigation_user_status", "异常")
	if err != nil {
		return
	}

	if err = global.GVA_DB.Table("epidemic_investigation_details").
		Where("abnormal=? and related_form_id=?", abnormal, req.Id).
		Count(&total).Error; err != nil {
		return
	}
	form.Abnormal = int(total)
	return db.Where("id=? ", req.Id).Select("abnormal", "status").Updates(&form).Error
}

// UpdateStatus 更新状态
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationFormService *EpidemicInvestigationFormService) UpdateStatus(bean epidemicReq.EpidemicInvestigationFormUpdateStatus) (err error) {
	db := global.GVA_DB
	if err = db.Where("id=?", bean.Id).Model(&epidemic.EpidemicInvestigationForm{}).
		Updates(map[string]interface{}{"status": bean.Status}).Error; err != nil {
		return err
	}
	// 通知异常人员涉疫登记
	closed, err := GetValueByKeyAndName("investigation_form_status", "关闭")
	if err != nil {
		return
	}
	abnormal, err := GetValueByKeyAndName("investigation_user_status", "异常")
	if err != nil {
		return
	}
	if bean.Status == closed {
		var to []string
		if err = db.Table("epidemic_investigation_details").Where("related_form_id=? and abnormal=?", bean.Id, abnormal).
			Select("mobile").
			Find(&to).Error; err != nil {
			return err
		}
		if err = msgsms.SendMsg(to, "a0683f74361c4c8abb4311663912e18c", "8819022138406", ""); err != nil {
			return
		}
	}
	return err
}
